//
//  JKBaseViewController.swift
//  ZhiHuDaily-Swift
//
//  Created by albert on 2018/3/2.
//  Copyright © 2018年 安永博. All rights reserved.
//

import UIKit
import SnapKit
import MJRefresh

class JKBaseViewController: UIViewController {
    
    // MARK: - 属性
    
    /** 使用frame布局tableView */
    public var tableViewUseFrame = false
    
    /** 使用frame布局contentView */
    public var contentViewUseFrame = false
    
    /** 容器view */
    lazy var contentView: UIView = {
        
        let contentView = UIView()
        
        view.insertSubview(contentView, at: 0)
        
        if contentViewUseFrame {
            
            contentView.frame = JKScreenBounds
            
        }else{
            
            contentView.translatesAutoresizingMaskIntoConstraints = false
            
            let cons1 = NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[contentView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["contentView" : contentView])
            view.addConstraints(cons1)
            
            let cons2 = NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[contentView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["contentView" : contentView])
            
            view.addConstraints(cons2)
        }
        
        return contentView
    }()
    
    /** 导航条背景view */
    lazy var navBgView: UIView = {
        
        let navBgView = UIView(frame: CGRect(x: 0, y: 0, width: JKScreenW, height: JKNavBarHeight))
        navBgView.isUserInteractionEnabled = true
        navBgView.backgroundColor = JKMainColor;
        
        return navBgView
    }()
    
    /** 导航条标题 */
    var navTitle: String?  {
        
        didSet{
            
            navigationItem.title = navTitle
        }
    }
    
    /** 导航返回文字 */
    var navBackTitle: String?  {
        
        didSet{
            
            navBackButton.setTitle(navBackTitle, for: UIControlState.normal)
        }
    }
    
    /** 当前属性列表保存的皮肤模式 */
    var currentSkinModel: String {
        
        return UserDefaults.standard.string(forKey: JKCurrentSkinModelKey) ?? JKDaySkinModelValue
    }
    
    /** 控制器当前皮肤模式 */
    var vcSkinModel: String = ""
    
    /** reloadIndicatorView */
    private lazy var reloadIndicatorView: UIActivityIndicatorView = {
        
        let indicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
        indicatorView.center = CGPoint(x: view.bounds.size.width * 0.5, y: view.bounds.size.height * 0.5)
        
        return indicatorView
    }()
    
    /** 重新加载的按钮 */
    lazy var reloadButton: UIView = {
        
        let reloadButton = UIButton(type: UIButtonType.custom)
        
//        reloadButton.frame = CGRect(x: 15, y: 0, width: view.frame.size.width - 30, height: view.frame.size.height)
        reloadButton.setTitle("加载数据失败，点击重新加载", for: UIControlState.normal)
        reloadButton.setTitleColor(UIColor.gray, for: UIControlState.normal)
        reloadButton.titleLabel?.font = UIFont.systemFont(ofSize: 12)
        
        reloadButton.addTarget(self, action: #selector(reloadNewData), for: UIControlEvents.touchUpInside)
        
        return reloadButton
    }()
    
    /** 重新加载的view */
    lazy var reloadView: UIView = {
        
        let reloadView = UIView(frame: view.bounds)
        
        reloadView.isHidden = true
        reloadView.isUserInteractionEnabled = true
        reloadView.backgroundColor = JKGlobalBgColor
        
        reloadView.addSubview(reloadButton)
        
        reloadView.addSubview(reloadIndicatorView)
        
        reloadButton.translatesAutoresizingMaskIntoConstraints = false
        
        let cons1 = NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[reloadButton]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["reloadButton" : reloadButton])
        reloadView.addConstraints(cons1)
        
        let cons2 = NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[reloadButton]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["reloadButton" : reloadButton])
        
        reloadView.addConstraints(cons2)
        
        view.addSubview(reloadView)
        
        return reloadView
    }()
    
    /** 返回按钮 */
    lazy var navBackButton: UIButton = {
        
        let button = UIButton(type: UIButtonType.custom)
        
        button.titleLabel?.font = UIFont.systemFont(ofSize: 16)
       
        button.setTitleColor(UIColor.white, for: UIControlState.normal)
        button.setTitleColor(UIColor.lightGray, for: UIControlState.highlighted)
        button.setImage(UIImage(named: "Back_White"), for: UIControlState.normal)
        button.setImage(UIImage(named: "Back"), for: UIControlState.highlighted)
//        button.backgroundColor = UIColor.red
        button.addTarget(self, action: #selector(navBackButtonClick), for: UIControlEvents.touchUpInside)
        
        // 让button里面的内容移到最左边
        button.contentHorizontalAlignment = UIControlContentHorizontalAlignment.left
        // 设置button的内容偏移，可以与上面的Alignment配合，也可以直接设置偏移量更大些，比如-10改为-80
        //button.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);//想让导航条的按钮距离边上更近些，可以用这个
        //        button.titleEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 0);
        button.imageEdgeInsets = UIEdgeInsets(top: 0, left: -8, bottom: 0, right: 0)
        //        button.backgroundColor = [UIColor redColor];
        // contentMode一般用来设置imageView，设置button没有用
        // button.contentMode = UIViewContentModeLeft;
        
        // 让button的大小适配里面的内容
        //        [button sizeToFit];
        button.height = 44
        button.width = 44
        
        // 设置返回按钮为自定义是没有反应的
        navigationItem.leftBarButtonItem = UIBarButtonItem(customView: button)
        
        return button
    }()
    
    
    /** plain样式tableView */
    lazy var tableViewPlain: JKBaseTableView = {
        
        let tableView = JKBaseTableView(frame: CGRect.zero, style: UITableViewStyle.plain)
        tableView.backgroundColor = nil
        contentView.insertSubview(tableView, at: 0)
        
        tableView.dataSource = self
        tableView.delegate = self
        
        tableView.rowHeight = 44
        tableView.sectionFooterHeight = 0
        tableView.sectionHeaderHeight = 0
        
        tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: CGFloat.leastNormalMagnitude, height: CGFloat.leastNormalMagnitude))
        tableView.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: CGFloat.leastNormalMagnitude, height: CGFloat.leastNormalMagnitude))
        
        tableView.scrollsToTop = true
        tableView.separatorStyle = UITableViewCellSeparatorStyle.none
        
        tableView.jk_adapt_iOS_11_scrollView()
        
        if tableViewUseFrame {
            
            tableView.frame = JKScreenBounds
            
        }else{
            
            tableView.translatesAutoresizingMaskIntoConstraints = false
            
            let cons1 = NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[tableView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["tableView" : tableView])
            contentView.addConstraints(cons1)
            
            let cons2 = NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[tableView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["tableView" : tableView])
            contentView.addConstraints(cons2)
        }
        
        return tableView
    }()
    
    /** grouped样式tableView */
    lazy var tableViewGrouped: JKBaseTableView = {
        
        let tableView = JKBaseTableView(frame: CGRect.zero, style: UITableViewStyle.grouped)
        tableView.backgroundColor = nil
        contentView.insertSubview(tableView, at: 0)
        
        tableView.dataSource = self
        tableView.delegate = self
        
        tableView.rowHeight = 44
        tableView.sectionFooterHeight = 0
        tableView.sectionHeaderHeight = 0
        
        tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: CGFloat.leastNormalMagnitude, height: CGFloat.leastNormalMagnitude))
        tableView.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: CGFloat.leastNormalMagnitude, height: CGFloat.leastNormalMagnitude))
        
        tableView.scrollsToTop = true
        tableView.separatorStyle = UITableViewCellSeparatorStyle.none
        
        tableView.jk_adapt_iOS_11_scrollView()
        
        if tableViewUseFrame {
            
            tableView.frame = JKScreenBounds
            
        }else{
            
            tableView.translatesAutoresizingMaskIntoConstraints = false
            
            let cons1 = NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[tableView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["tableView" : tableView])
            contentView.addConstraints(cons1)
            
            let cons2 = NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[tableView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["tableView" : tableView])
            contentView.addConstraints(cons2)
        }
        
        return tableView
    }()
    
    // MARK:- 生命周期方法
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        NotificationCenter.default.addObserver(self, selector: #selector(updateSkin), name: NSNotification.Name(rawValue: JKSkinModelDidChangedNotification), object: nil)
        
        updateSkin()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: JKSkinModelDidChangedNotification), object: nil)
    }
    
    // MARK: - 初始化
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        automaticallyAdjustsScrollViewInsets = false
        
        view.backgroundColor = JKGlobalBgColor
        view.insertSubview(navBgView, aboveSubview: contentView)
        
        if (navTitle != nil) {
            
            navigationItem.title = navTitle
        }
        
        jk_setupNav()
        
        setupNav()
        
        setup()
        
        setupTableView()
        
        loadNewData()
    }
    
    private func jk_setupNav() {
        
//        let count = navigationController?.childViewControllers.count
//        
//        if (count! < 2) {
//            return;
//        }
        
        navBackButton.isEnabled = true
    }
    
    /** 点击导航返回按钮 */
    @objc func navBackButtonClick() {
        
        navigationController?.popViewController(animated: true)
    }
    
    public func is3DTouchAvailable() -> Bool {
        
        if #available(iOS 9.0, *) {
            
            return traitCollection.forceTouchCapability == UIForceTouchCapability.available
            
        }else{
            
            return false
        }
        
    }
    
    public func showReloadView() {
        
        if !reloadView.isHidden {
            
            reloadIndicatorView.stopAnimating()
            reloadButton.isHidden = false
            
            return
        }
        
        view.bringSubview(toFront: reloadView)
        reloadIndicatorView.center = CGPoint(x: reloadView.frame.width * 0.5, y: reloadView.frame.height * 0.5)
        
        reloadView.transform = CGAffineTransform(scaleX: 0.01, y: 0.01)
        reloadView.isHidden = false
        
        UIView.animate(withDuration: 0.25) {
            
            self.reloadView.transform = CGAffineTransform.identity
        }
    }
    
    public func hideReloadView() {
        
        reloadIndicatorView.stopAnimating()
        
        UIView.animate(withDuration: 0.25, animations: {
            
            self.reloadView.transform = CGAffineTransform(scaleX: 0.01, y: 0.01)
            
        }) { (_) in
            
            self.reloadView.isHidden = true
            self.reloadButton.isHidden = false
        }
    }
    
    @objc private func reloadNewData() {
        
        reloadButton.isHidden = true
        reloadIndicatorView.startAnimating()
        
        loadNewData()
    }
    
    func setupNav() {}
    
    func setup() {}
    
    func setupTableView() {}
    
    @objc func loadNewData() {}
    
    @objc func loadMoreData() {}


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    deinit {
        
        NotificationCenter.default.removeObserver(self)
        
        JKLog(message: "deinit")
        
    }

}

// MARK: - taleview数据源

extension JKBaseViewController: UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
        
        return cell!
    }
}


// MARK: - taleview代理

extension JKBaseViewController: UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        return CGFloat.leastNormalMagnitude
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        
        return CGFloat.leastNormalMagnitude;
    }
}

extension JKBaseViewController: JKUpdateSkinProtocol {
    
    func updateSkin() {
        
        if vcSkinModel == currentSkinModel {
            return
        }
        
        self.vcSkinModel = self.currentSkinModel
        
        if self.vcSkinModel == JKNightSkinModelValue { // 夜间模式
            
            self.view.backgroundColor = JKNightSkinBgColor
            self.navBgView.backgroundColor = JKNightSkinNavColor
            self.navigationController?.navigationBar.tintColor = JKSameRGBColor(186)
            self.navBackButton.setTitleColor(JKColor(186, 186, 186), for: UIControlState.normal)
            
            self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor : JKSameRGBColor(186), NSAttributedStringKey.font: UIFont.systemFont(ofSize: 18)]
            
        }else{ // 日间模式
            
            self.view.backgroundColor = JKGlobalBgColor
            self.navBgView.backgroundColor = JKMainColor
            self.navigationController?.navigationBar.tintColor = UIColor.white
            self.navBackButton.setTitleColor(UIColor.white, for: UIControlState.normal)
            
            self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor : UIColor.white, NSAttributedStringKey.font: UIFont.systemFont(ofSize: 18)]
        }
    }
}



